<%@ page language="java"
  import="java.util.ArrayList,
    java.util.Locale,
    org.pentaho.core.ui.SimpleUrlFactory,
    org.pentaho.core.system.PentahoSystem,
    org.pentaho.core.solution.HttpRequestParameterProvider,
    org.pentaho.core.solution.HttpSessionParameterProvider,
    org.pentaho.core.session.IPentahoSession,
    org.pentaho.messages.Messages,
    org.pentaho.core.util.UIUtil,
    org.pentaho.core.util.IUITemplater,
	org.pentaho.util.VersionHelper,
	org.pentaho.messages.util.LocaleHelper,
    org.pentaho.core.solution.ActionResource,
    org.pentaho.core.solution.IActionResource,
    org.pentaho.ui.component.INavigationComponent,
    org.pentaho.ui.component.NavigationComponentFactory,
    org.pentaho.core.repository.ISolutionRepository,
    org.pentaho.core.solution.SimpleParameterProvider,
    org.pentaho.ui.ChartHelper,
	java.io.*"
	 %><%

/*
 * This software is provided under the terms
 * of GNU Lesser GPL License. You may not use
 * this file except in compliance with the license. If you need a copy of the license,
 * please go to http://www.gnu.org/copyleft/lesser.html. 
 * This code uses the Pentaho BI Platform API. 
 
 * @author Fabio D'Ovidio
*/

	response.setCharacterEncoding(LocaleHelper.getSystemEncoding());
	HttpSession httpSession = request.getSession();

	String baseUrl = PentahoSystem.getApplicationContext().getBaseUrl();

	IPentahoSession userSession = UIUtil.getPentahoSession( request );

	HttpRequestParameterProvider requestParameters = new HttpRequestParameterProvider( request );
	HttpSessionParameterProvider sessionParameters = new HttpSessionParameterProvider( userSession );

	String solution = "dashboards";

	requestParameters.setParameter("solution",solution);
	requestParameters.setParameter("path","");
	String hrefUrl = baseUrl; 
	String onClick = ""; 

	SimpleUrlFactory urlFactory = new SimpleUrlFactory( hrefUrl );
	ArrayList messages = new ArrayList();


	// Is googleMaps enabled?
    boolean isGoogleMapsEnabled = false;
  // TO DO
  //  if ()
  //  	isGoogleMapsEnabled = true;

	
	String dashboardContent = "";

	if(requestParameters.getParameter("dashboard") != null){
		String dashboard = requestParameters.getParameter("dashboard").toString();
		
    ActionResource resource = new ActionResource( "", IActionResource.SOLUTION_FILE_RESOURCE, "text/xml", "dashboards/" + dashboard +"/template.html" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    
		try {
			
      dashboardContent = PentahoSystem.getSolutionRepository(userSession).getResourceAsString( resource );
			
		} catch (Throwable t) {
		}
	}
    if(isGoogleMapsEnabled){
    
    	
		String googleMapsApiKey = PentahoSystem.getSystemSetting("google/googlesettings.xml", "google_maps_api_key", null); 
        
        // TO DO !!
    }
    

// Get System Settings
String layerGeostat = PentahoSystem.getSystemSetting("GeoBI/geobi.xml", "layer", null); 
String nameAttribute = PentahoSystem.getSystemSetting("GeoBI/geobi.xml", "nameatt", null); 
String indicators = PentahoSystem.getSystemSetting("GeoBI/geobi.xml", "param", null); 
String mapName = PentahoSystem.getSystemSetting("GeoBI/geobi.xml", "map", null);
String propAtt = PentahoSystem.getSystemSetting("GeoBI/geobi.xml", "att", null);
String geocodid = PentahoSystem.getSystemSetting("GeoBI/geobi.xml", "geocode", null);


String[] layersProp  = layerGeostat.split(";");
String cat = layersProp[1];
String[] indicator  = indicators.split(";");
String[] propAtts  = propAtt.split(";");

int nindic = indicator.length;
int npatt = propAtts.length;
String id = geocodid;


%>

<%= dashboardContent %>
 <script type="text/javascript">
  

    //<![CDATA[
  Ext.onReady(function() {
      Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
      
      map = new OpenLayers.Map($('olmap'));
      this.map = map;
      
      var jpl_wms = new OpenLayers.Layer.WMS("Satellite",
                                             "http://labs.metacarta.com/wms-c/Basic.py?", 
                                             {layers: 'satellite', format: 'image/png'});

      vmap0 = new OpenLayers.Layer.WMS("OpenLayers WMS",
                                           "http://labs.metacarta.com/wms/vmap0", 
                                           {layers: 'basic'});
    
      map.addLayers([vmap0, jpl_wms]);    
      
      
	   	var propSymbol;
      
  function showDetails(regDesc) {
	    var infoPanel = Ext.getCmp('south-panel');
     
      infoPanel.body.dom.innerHTML = "<table><tr><td>" + pentahoAction( "dashboards", "GeoBI", "pie.xaction", 
                            new Array( 
                            new Array( "regione", regDesc)
                            )
                            );
     
  }       
    
   <%
     
      if("prop".equals(cat) ){

      String[] layer = layersProp[0].split("-");
      
      String layerNameDef = layer[0];
      
      String layerDispl =  layer[1];

     
     %> 

      
      // define proportional symbol layer and its syling
      propSymbolLayer = [propSymbolLayer];
      propSymbolLayer = new OpenLayers.Layer.Vector('<%=layerDispl%>', {
          'visibility': false,
          
          'styleMap': new OpenLayers.StyleMap({
              'select': new OpenLayers.Style(
                  {'strokeColor': 'red', 'cursor': 'pointer'}
              )
          })
      });
     
     map.addLayers([propSymbolLayer]);

      

      var selectPropSymbol2 = selectControl = new OpenLayers.Control.SelectFeature(propSymbolLayer,
                {onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
      map.addControl(selectPropSymbol2); 
      selectPropSymbol2.activate();
 
      
      propSymbol = new mapfish.widgets.geostat.ProportionalSymbol({
                                map: map,
                                
                                layer: propSymbolLayer,
                                
                                title: 'Proportional Symbols',
                                
                                nameAttribute: "<%=nameAttribute%>",
                                
                                
                                indicators: [
                                <%
                                for( int k=0; k<nindic; k++ ) {
                                String[] indicat = indicator[k].split("-");
                                String name = indicat[0];
                                String field = indicat[1];

                                %>
                                ['<%=name%>', '<%=field%>']<% if( k != nindic-1 ) {out.println(",");}%>
                                <%}%>
                                             
                                             ],
                                
                                
                                'url': '/pentaho/MapOl?layer=<%=layerNameDef%>&id=<%=id%>',
                                
                                featureSelection: false,
                                loadMask : {msg: 'Caricamento...', msgCls: 'x-mask-loading'},
                                defaults: {
                                    width: 130
                                },
                                listeners: {
                                    collapse: {
                                        // hide layer if collapsed
                                        fn: function() {
                                            //this.layer.setVisibility(false);
                                        //this.layer.redraw();
                                        }
                                    },
                                    expand: {
                                        // show layer if expanded
                                        fn: function() {
                                            if (this.classificationApplied) {
                                                //this.layer.setVisibility(true);
                                            }
                                        }
                                    }
                                }
                            });

  function onFeatureSelect(feature) {
            selectedFeature = feature;
			content =                "<div style='font-size:.8em'>"+
                                     <%
                                     
                                     String featValue = "";
                                     String featDesc = "";
                                     String regDesc = "";
                                     for(int d = 0; d<npatt; d++){
                                     
                                     String[] attc = propAtts[d].split("-");
                                     
                                     String attcname = attc[0];
                                     
                                     String attcdef =  attc[1];
                                     if(d==0){
                                     featValue=attcdef;
                                     featDesc=attcname;
                                     }
                                     if(d==2){
                                     regDesc=attcdef;
                                     }
                                     
                                     %>
                                      "<b><%=attcname%></b>: " + feature.attributes['<%=attcdef%>'] + "<br />"+
                                     <%}%>"";
                                     
                                     dialValue = feature.attributes['<%=featValue%>'];
                                     regDescValue = feature.attributes['<%=regDesc%>'];
			pentahoContent = pentahoAction( "dashboards", "GeoBI", "dial.xaction", 
				            new Array( 
                            new Array( "customer", "<%=featDesc%>"), //this.data[0]
					        new Array( "value", dialValue),  //this.data[1]
                            new Array( "max", 30),
					        new Array( "low", 5 ),
					        new Array( "high", 15 )
				          )				           
			            )+"</div>";  
			                    
                          
                          showDetails(regDescValue);                    
                          
            popup = new OpenLayers.Popup.FramedCloud("chicken", 
                                     feature.geometry.getBounds().getCenterLonLat(),
                                     null,
                      content + pentahoContent,
                                     null, true, onPopupClose);
            feature.popup = popup;
            map.addPopup(popup);
        }

         
 <%
 } 
 
    else if("chorop".equals(cat) ){

      String[] layer = layersProp[0].split("-");
      
      String layerNameDef = layer[0];
      
      String layerDispl =  layer[1];
      
      %> 
      
      // define choropleth layer and its syling
      var choroplethLayer = new OpenLayers.Layer.Vector('<%=layerDispl%>', {
          'visibility': false,
          'styleMap': new OpenLayers.StyleMap({
              'default': new OpenLayers.Style(
                  OpenLayers.Util.applyDefaults(
                      {'fillOpacity': 0.5},
                      OpenLayers.Feature.Vector.style['default']
                  )
              ),
              'select': new OpenLayers.Style(
                  {'strokeColor': 'red', 'cursor': 'pointer'}
              )
          })
      });
     
     map.addLayer(choroplethLayer);  

      var selectChoropleth = selectControl =new OpenLayers.Control.SelectFeature(choroplethLayer,
          
                   {onSelect: onFeatureSelect, onUnselect: onFeatureUnselect}
      );
      map.addControl(selectChoropleth);
      selectChoropleth.activate();
      
      propSymbol = new mapfish.widgets.geostat.Choropleth({
                              map: map,
                              layer: choroplethLayer,
                              title: 'Choropleths',
                              nameAttribute: "<%=nameAttribute%>",
                              
                              indicators: [
                              <%
                                for( int r=0; r<nindic; r++ ) {
                                String[] indicatc = indicator[r].split("-");
                                String namec = indicatc[0];
                                String fieldc = indicatc[1];

                                %>

                                ['<%=namec%>', '<%=fieldc%>']<% if( r != nindic-1 ) {out.println(",");}%>
                                <%}%>

                              ],
                              
                              'url': '/pentaho/MapOl?layer=<%=layerNameDef%>&id=<%=id%>',
                              
                              featureSelection: false,
                              loadMask : {msg: 'Loading Data...', msgCls: 'x-mask-loading'},
                              defaults: {
                                  width: 130
                              },
                              listeners: {
                                  collapse: {
                                      // hide layer if collapsed
                                      fn: function() {
                                         // this.layer.setVisibility(false);
                                      }
                                  },
                                  expand: {
                                      // show layer if expanded
                                      fn: function() {
                                          if (this.classificationApplied) {
                                            //  this.layer.setVisibility(true);
                                          }
                                      }
                                  }
                              }
                          });
      
   
     
     
     
     


  function onFeatureSelect(feature) {
            selectedFeature = feature;
			content =                      "<div style='font-size:.8em'>"+
                                     <%
                                     
                                     String featValue = "";
                                     String featDesc = "";
                                     String regDesc = "";
                                     for(int d = 0; d<npatt; d++){
                                     
                                     String[] attc = propAtts[d].split("-");
                                     
                                     String attcname = attc[0];
                                     
                                     String attcdef =  attc[1];
                                     if(d==0){
                                     featValue=attcdef;
                                     featDesc=attcname;
                                     }
                                     if(d==2){
                                     regDesc=attcdef;
                                     }
                                     
                                     %>
                                      "<b><%=attcname%></b>: " + feature.attributes['<%=attcdef%>'] + "<br />"+
                                     <%}%>"";
                                     
                                    dialValue = feature.attributes['<%=featValue%>'];
                                    regDescValue = feature.attributes['<%=regDesc%>'];
                                    pentahoContent = pentahoAction( "dashboards", "GeoBI", "dial.xaction", 
                                      new Array( 
                                      new Array( "customer", "<%=featDesc%>"), 
                                      new Array( "value", dialValue),  
                                      new Array( "max", 30),
                                      new Array( "low", 5 ),
                                      new Array( "high", 15 )
                                    )				           
                                  )+"</div>";  
			                    
                          
                                    showDetails(regDescValue);                    
                          
                                    popup = new OpenLayers.Popup.FramedCloud("chicken", 
                                    feature.geometry.getBounds().getCenterLonLat(),
                                    null,
                                    content + pentahoContent,
                                    null, true, onPopupClose);
                                    feature.popup = popup;
                                    map.addPopup(popup);
        }


      
      
     <%
     }
      

 
 else { %> 
 
 Ext.Msg.alert( 'Status', 'No category is set! Set one!' );
 
<%}%>
 

      
      map.setCenter(new OpenLayers.LonLat(6.090, 40.373), 5);

    
      vectorLayer = new OpenLayers.Layer.Vector("vector", { 
                displayInLayerSwitcher: false
            });
            map.addLayer(vectorLayer);

            
            
       toolbar = new mapfish.widgets.toolbar.Toolbar({
                map: map, 
                configurable: false
            });
      
 
  
      // create viewport
      var viewport = new Ext.Viewport({
          layout: 'border',
          items:[
              new Ext.BoxComponent({ // raw
                  region: 'north',
                  el: 'north',
                  height: 52
              }),{
                  region: 'south',
                  contentEl: 'south',
                  id: 'south-panel',
                  split: true,
                  height: 200,
                  minSize: 100,
                  maxSize: 200,
                  collapsible: true,
                  title: 'Results and Diagrams',
                  margins: '0 0 0 0'
              },{
                  region: 'east',
                  title: 'Layers',
                  width: 200,
                  collapsible: true,
                  collapsed: true,
                  margins: '0 0 0 5',
                  defaults: {
                    border: true,
                    frame: true
                  },
                  layout: 'border',
                  items: [{
                      title: 'Layers  tree',
                      region: 'north',
                      autoHeight: true,
                      xtype: 'layertree',
                      map: map
                  },{
                      title: 'Overview Map',
                      region: 'center',
                      html:'<div id="overviewmap"></div>'+'<div id="legend"></div>'
                      
                  },{
                      title: 'Position',
                      region: 'south',
                      collapsible: true,
                      height: 65,
                      contentEl: 'position'
                  }]
              },{
                  region: 'west',
                  id: 'west-panel',
                  title: 'Analysis',
                  split: true,
                  collapsible: true,
                  width: 250,
                  minSize: 175,
                  maxSize: 500,
                  margins: '0 0 0 5',
                  layout: 'accordion',
                  defaults: {
                    border: true,
                    frame: true
                  },
                  items: propSymbol
              },{
                  region: 'center',
                  title: '<%=mapName%>',
                  xtype: 'mapcomponent',
                  map: map,
                  tbar: toolbar
              }
           ]
      });
      this.viewport=viewport;

 
      map.addControl(new OpenLayers.Control.MousePosition({displayClass: "void", 
                                                           div: $('mouseposition'), 
                                                           prefix: 'x: ',
                                                           separator: '<br/>y: '}));
  
      map.addControl(new OpenLayers.Control.OverviewMap({div: $('overviewmap')}));
      //TO DO
      initToolbarContent(); 
      Ext.get('loading').fadeOut({remove: true});
            
           
            
  });

  //]]>
    </script>






